import React from 'react'
import ReactDOM from 'react-dom'
import { browserHistory, Router } from 'react-router'
import { Provider } from 'react-redux'
import {syncHistoryWithStore} from 'react-router-redux'
import createStore from './store/createStore'
import injectTapEventPlugin from 'react-tap-event-plugin'
import app from '../../nmb/app'
import clientConfig from './params/config'
import rely from 'nmb/oauth2/oauth2rely'

// ========================================================
// Store Instantiation
// ========================================================
const initialState = window.___INITIAL_STATE__;
const store = createStore(browserHistory, initialState);
const routes = require('./routes/index').default(store);
const history = syncHistoryWithStore(browserHistory, store);

// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('root')

let render = () => {
    ReactDOM.render(
        <Provider store={store}>
            <Router history={history} routes={routes}/>
        </Provider>,
        MOUNT_NODE
    )
}

// ========================================================
// Developer Tools Setup
// ========================================================
if (__DEV__) {
  if (window.devToolsExtension) {
    window.devToolsExtension.open()
  }
}

// This code is excluded from production bundle
if (__DEV__) {
  if (module.hot) {
    // Development render functions
    const renderApp = render
    const renderError = (error) => {
      const RedBox = require('redbox-react').default

      ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
    }

    // Wrap render in try/catch
    render = () => {
      try {
        renderApp()
      } catch (error) {
        renderError(error)
      }
    }

    // Setup hot module replacement
    module.hot.accept('./routes/index', () =>
      setImmediate(() => {
        ReactDOM.unmountComponentAtNode(MOUNT_NODE)
        render()
      })
    )
  }
}

// ========================================================
// Go!
// react-tap-event-plugin support
// ========================================================
injectTapEventPlugin();
// set client identity
app.params = Object.assign(app.params, clientConfig);
// set oauth params
rely.defaultParams = Object.assign(rely.defaultParams, require('./params/oauth2').default);
render();
